<?php
/*
 * +----------------------------------------------------------------------
 * 作 者: xinglou <xinglou1@foxmail.com>
 * +----------------------------------------------------------------------
 * 创建日期：2015-06-24
 * +----------------------------------------------------------------------
 * 文件描述：公用方法
 * +----------------------------------------------------------------------
 * 升级记录：
 * +----------------------------------------------------------------------
 */
header("Content-Type: text/html; charset=utf-8");

class CommonAction extends Action
{

    /**
     * 初始化方法
     */
    public function _initialize()
    {
        // 查询用户基本信息
        $data = get_admin_info();
        $this->assign('login_user_info', $data);
        if (empty($data['userid'])) {
            redirect(C('LOGIN_URL'));
        }
    }

    /**
     * 系统后台菜单
     */
    public function menu()
    {
        $model = new PageModel();
        if ($this->get_user_name() === C('ADMIN_NAME')) {
            $list = $model->field("id,
									parentid,
									name,
									url,
									target,
									ico,
									mark")
                ->where("parentid = '0'
							   and status = 'a'")
                ->order('seq')
                ->select();
            foreach ($list as $key => $value) {
                $list[$key]['sub'] = $model->field("id,
													parentid,
													name,
													url,
													target,
													ico,
													mark")
                    ->where("parentid = '" . $value['id'] . "'
										   		and status = 'a'")
                    ->order("seq")
                    ->select();
            }
        } else {
            $userid = $this->get_userid();
            $list = $model->table("page a,
								   role_page b,
								   user_role c")
                ->field("a.id,
									a.parentid,
									a.name,
									a.url,
									a.target,
									a.ico,
									a.mark")
                ->where("a.id = b.pageid
					 		   and b.roleid = c.roleid
					 		   and a.status = 'a'
					 		   and a.parentid = '0'
					 		   and c.userid = '" . $userid . "'")
                ->order('a.seq')
                ->select();
            foreach ($list as $key => $value) {
                $list[$key]['sub'] = $model->table("page a,
												    role_page b,
												    user_role c")
                    ->field("a.id,
													a.parentid,
													a.name,
													a.url,
													a.target,
													a.ico,
													a.mark")
                    ->where("a.id = b.pageid
									 		    and b.roleid = c.roleid
									 		    and a.status = 'a'
									 		    and a.parentid = '" . $value['id'] . "'
									 		    and c.userid = '" . $userid . "'")
                    ->order('a.seq')
                    ->select();
            }
        }
        $this->assign('menu_list', $list);
        $this->display('Public:menu');
    }

    /**
     * 生成分页所需信息
     * 
     * @param $model 模型            
     * @param string $sortBy
     *            默认排序字段
     * @param boolean $asc
     *            默认排序方式
     * @return 分页所需信息
     */
    protected function _page($model, $sortBy = '', $asc = 'asc')
    {
        $page = array();
        $page['order'] = ! empty($sortBy) ? $sortBy : $model->getPk(); // 排序字段，优先是$this->_request('_order')， 然后是$sortBy参数，最后默认为主键名
        $page['sort'] = $asc == 'asc' ? 'asc' : 'desc'; // 排序规则
                                                        
        // 分页大小，默认是C("PAGESIZE")
        if (! empty($_REQUEST['numPerPage'])) {
            $page['listRows'] = $this->_request('numPerPage');
        } else {
            $page['listRows'] = C("PAGESIZE");
        }
        $this->request['numPerPage'] = $page['listRows']; // 继续传值
        return $page;
    }

    /**
     * 删除指定地址下的文件
     * 
     * @param string $path
     *            文件路径
     */
    public function delFile($path)
    {
        try {
            if (file_exists($path)) {
                unlink($path);
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * 时间格式转换 秒---时：分：秒
     * 
     * @param int $seconds            
     * @return 格式化时间
     */
    function changeTimeType($seconds)
    {
        if ($seconds > 3600) {
            $hours = intval($seconds / 3600);
            $minutes = $seconds / 600;
            $time = $hours . ":" . gmstrftime('%M:%S', $minutes);
        } else {
            $time = gmstrftime('%H:%M:%S', $seconds);
        }
        return $time;
    }

    /**
     * 获取登录用户ID
     * 
     * @return 用户ID
     */
    function get_userid()
    {
        return cookie('userid');
    }

    /**
     * 获取登录用户名
     * 
     * @return 用户名
     */
    function get_user_name()
    {
        return cookie('user_name');
    }

    /**
     * 获取登录用户真实姓名
     * 
     * @return 用户真实姓名
     */
    function get_user_real_name()
    {
        return cookie('user_real_name');
    }

    /**
     * 获取系统日期
     * 
     * @return 例如：2016-07-18 04:08:36
     */
    function get_date()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * 文件夹打包成zip文件
     * 
     * @param string $path            
     * @param string $zip            
     */
    function addFileToZip($path, $zip)
    {
        $handler = opendir($path); // 打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") { // 文件夹文件名字为'.'和‘..’，不要对他们进行操作
                if (is_dir($path . "/" . $filename)) { // 如果读取的某个对象是文件夹，则递归
                    $this->addFileToZip($path . "/" . $filename, $zip);
                } else { // 将文件加入zip对象
                    $zip->addFile($path . "/" . $filename);
                }
            }
        }
        @closedir($path);
    }

    /**
     * 移动文件夹
     * 
     * @param string $source            
     * @param string $target            
     */
    function move_d($source, $target)
    {
        if (is_dir($source)) {
            $dest_name = basename($source);
            $creat_dir = $target . "/" . $dest_name;
            if (! is_dir($creat_dir)) {
                mkdir($creat_dir, 0777);
            }
            $d = dir($source);
            while (($entry = $d->read()) !== false) {
                if (is_dir($source . "/" . $entry)) {
                    if ($entry == "." || $entry == "..") {
                        continue;
                    } else {
                        $se = $source . "/" . $entry;
                        $td = $target . "/" . $dest_name;
                        $this->move_d($se, $td);
                    }
                } else {
                    $se = $source . "/" . $entry;
                    $tde = $target . "/" . $dest_name . "/" . $entry;
                    copy($se, $tde);
                }
            }
        } else {
            $se = $source . "/" . $entry;
            $td = $target . "/" . $dest_name;
            copy($se, $td);
        }
        // 删除源目录
        $this->delDir($source);
        return true;
    }

    /**
     * 删除整个目录
     * 
     * @param
     *            $dir
     * @return bool
     */
    function delDir($dir)
    {
        // 先删除目录下的所有文件：
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (! is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    $this->delDir($fullpath);
                }
            }
        }
        closedir($dh);
        // 删除当前文件夹：
        return rmdir($dir);
    }

    /**
     * 去除html标签、css样式、js、空格等格式的功能(格式化html文本)也有截取字符串的功能。
     * 
     * @param string $string
     *            字符串
     * @param int $sublen
     *            截取字符串长度
     * @return string 字符串
     */
    function cutstr_html($string, $sublen)
    {
        $string = strip_tags($string);
        $string = preg_replace('/\n/is', '', $string);
        $string = preg_replace('/ |　/is', '', $string);
        $string = preg_replace('/&nbsp;/is', '', $string);
        preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $t_string);
        if (count($t_string[0]) - 0 > $sublen) {
            $string = join('', array_slice($t_string[0], 0, $sublen)) . "…";
        } else {
            $string = join('', array_slice($t_string[0], 0, $sublen));
        }
        return $string;
    }

    /**
     * 获取问卷基本信息
     * 
     * @param string $formid            
     * @return array
     */
    public function get_form_info($formid)
    {
        $model = new FormModel();
        $data = $model->field("id,
							   title,
							   intro,
							   seq,
							   get_user_name(operator) operator,
							   update_date")
            ->where("id = '" . $formid . "'")
            ->find();
        return $data;
    }

    /**
     * 获取分组名称
     * 
     * @return array
     */
    public function get_groups_list()
    {
        $model = new GroupsModel();
        $data = $model->field("id,
							   concat(code, ' [', get_field_dict_name('groups','type',type), ']', name) name")->select();
        return $data;
    }

    /**
     * 获取问卷名称
     * 
     * @return array
     */
    public function get_form_list()
    {
        $model = new FormModel();
        $data = $model->field("id,
							   title")->select();
        return $data;
    }

    /**
     * 获取学校名称
     * 
     * @return array
     */
    public function get_school_list()
    {
        $model = new SchoolModel();
        $data = $model->field("id,
							   name")->select();
        return $data;
    }

    /**
     * 获取题项名称
     * 
     * @return array
     */
    public function get_question_test_select_list()
    {
        $model = new QuestionTestSelectModel();
        $data = $model->field(" id,
		                        code,
		                        get_field_dict_name('question_test_select', 'type', type) type,
								formid,
								question,
								score")->

        select();
        /*
         * $model = new SchoolModel();
         * $data = $model->field("id,
         * name")
         * ->select();
         */
        return $data;
    }

    /**
     * 获取数据字典中含义
     * 
     * @param unknown $table_naem            
     * @param unknown $field_name            
     * @return Ambigous <mixed, NULL, multitype:Ambigous <unknown, string> unknown , unknown, multitype:Ambigous <unknown, string> Ambigous <multitype:> >
     */
    public function get_field_dict_value($table_naem, $field_name, $field_value)
    {
        $model = new FieldDictModel();
        $value = $model->where("table_name = '" . $table_naem . "' and field_name = '" . $field_name . "' and field_value = '" . $field_value . "'")->getField('field_mean');
        return $value;
    }
    public function get_field_dict_remark($table_naem, $field_value)
    {
    	$model = new FieldDictModel();
    	$value = $model->where("table_name = '" . $table_naem . "'  and field_value = '" . $field_value . "'")->getField('remark');
    	return $value;
    }
	//查询一级指标对应二级指标的和
    public function get_second_quota_remark_all($field_value){
    	$quota_model = new QuotaModel();
    	$second_quota_data = $quota_model->field("second_quota")->where("first_quota='".$field_value."'")->group("second_quota")->select();
    	//二级指标分数
    	$second_quota_remark_data = array();
    	foreach($second_quota_data as $key=>$value){
    		$second_quota_remark_data[$key] = (float)$this->get_field_dict_remark("quota",$value['second_quota']);
    	}
    	return array_sum($second_quota_remark_data);
	}
    /**
     * 图表获取颜色
     * 
     * @param int $i            
     * @return RGB颜色代码 <string>
     */
    public function get_color($i)
    {
        $color = array(
            '#7cb5ec',
            '#434348',
            '#90ed7d',
            '#f7a35c',
            '#8085e9',
            '#f15c80',
            '#e4d354',
            '#44A9A8',
            '#8d4653',
            '#91e8e1'
        );
        return $color[$i % count($color)];
    }

    /**
     * 数字和大写字符互转
     * 
     * @param string $in            
     */
    public function char_num_exchange($in)
    {
        $out = '';
        if ($in >= '0' && $in <= '9') {
            $out = chr(ord($in) + 17);
        } elseif ($in >= 'A' && $in <= 'J') {
            $out = chr(ord($in) - 17);
        }
        if (empty($out)) {
            $out = $in;
        }
        return $out;
    }
}
?>